﻿using System;
using System.Collections.Generic;
using XmlTypes;
namespace CxExtension
{

	public static class StringExtension
	{

		/// <summary>
		/// if self or default value any one has content then return true,otherwise return false
		/// </summary>
		/// <param name="self"></param>
		/// <param name="defaultValue"></param>
		/// <param name="resultValue"></param>
		/// <returns></returns>
		public static bool HasValueOrDefault(this string self, string defaultValue,out string resultValue)
		{
			var value = self.IsNullOrEmpty()?defaultValue:self;
			resultValue = value;
			return value.HasValue();
		}
		public static bool HasValue(this string self)
		{
			return string.IsNullOrEmpty(self) == false;
		}

		public static bool IsNullOrEmpty(this string self)
		{
			return string.IsNullOrEmpty(self);
		}

		public static int Compare(string a, string b)
		{
			if (a.Length == b.Length)
			{
				return string.CompareOrdinal(a, b);
			}
			return a.Length - b.Length;
		}
		/// <summary>
		/// 数组分隔符： ','
		/// </summary>
		private const char LIST_SPRITER = ',';
		/// <summary>
		/// 将列表字符串转换为字符串的列表对象。
		/// </summary>
		/// <param name="strList">列表字符串</param>
		/// <param name="listSpriter">数组分隔符</param>
		/// <returns>列表对象</returns>
		public static List<string> ParseList(this string strList, char listSpriter = LIST_SPRITER)
		{
			var result = new List<string>();
			if (string.IsNullOrEmpty(strList))
				return result;

			var trimString = strList.Trim();
			if (string.IsNullOrEmpty(strList))
			{
				return result;
			}
			var detials = trimString.Split(listSpriter);//.Substring(1, trimString.Length - 2)
			foreach (var item in detials)
			{
				if (!string.IsNullOrEmpty(item))
					result.Add(item.Trim());
			}

			return result;
		}
		public static object ParseValue(this string self, Type type)
		{
			if (type == null)
				return null;
			if (type == typeof(string))
				return self;
			else if (type.IsGenericType)
			{
				Type gnType = type.GetGenericTypeDefinition();//取得模板类型
				var result = type.GetConstructor(Type.EmptyTypes).Invoke(null);
				if (gnType == typeof(List<>))
				{
					Type argumentsType = type.GetGenericArguments()[0];//取得 List<T>中 T的类型
					var list = self.ParseList();
					foreach (var item in list)
					{
						var v = item.ParseValue(argumentsType);
						type.GetMethod("Add").Invoke(result, new object[] { v });
					}
				}
				return result;
			}
			else
			{
				var parse = type.ParseMethod();
				if (parse != null)
				{
					object[] param = { self };
					var v = parse.Invoke(null, param);
					return v;
				}
			}
			return null;
		}
		public static T ParseValue<T>(this string self)
		{
			Type type = typeof(T);
			object value = self.ParseValue(type);
			return (T)value;
		}
	}
}
